<template>
  <div class="admin-layout">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="240px" class="sidebar">
        <div class="logo">
          <h3>视频管理系统</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-dark"
          router
        >
          <el-menu-item index="/dashboard">
            <el-icon><Document /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>
          <el-menu-item index="/categories">
            <el-icon><Menu /></el-icon>
            <span>视频类别管理</span>
          </el-menu-item>
          <el-menu-item index="/video-types">
            <el-icon><VideoCamera /></el-icon>
            <span>视频类型管理</span>
          </el-menu-item>
          <el-menu-item index="/videos">
            <el-icon><VideoPlay /></el-icon>
            <span>视频管理</span>
          </el-menu-item>
          <el-menu-item index="/comments">
            <el-icon><ChatRound /></el-icon>
            <span>评论管理</span>
          </el-menu-item>
          <el-menu-item index="/users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/settings">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <span>管理员控制台</span>
          </div>
          <div class="header-right">
            <span class="user-info">{{ userInfo.username }}</span>
            <el-button type="text" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>
        </el-header>

        <!-- 内容区 -->
        <el-main class="main-content">
          <div class="management-content">
            <h2>视频管理</h2>
            <div class="section-title">管理平台上的视频内容</div>
            
            <div class="search-bar">
              <div class="search-filters">
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索视频标题"
                  prefix-icon="el-icon-search"
                  style="width: 300px; margin-right: 10px;"
                  @keyup.enter="handleSearch"
                ></el-input>
                <el-select
                  v-model="statusFilter"
                  placeholder="选择状态"
                  style="width: 120px; margin-right: 10px;"
                >
                  <el-option label="全部" :value="null"></el-option>
                  <el-option label="已发布" :value="1"></el-option>
                  <el-option label="草稿" :value="0"></el-option>
                </el-select>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleResetFilter">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
              <div class="action-buttons">
                <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">
                  <el-icon><Delete /></el-icon>
                  批量删除 ({{ multipleSelection.length }})
                </el-button>
                <el-button type="primary" @click="handleUploadVideo">
                  <el-icon><Upload /></el-icon>
                  上传视频
                </el-button>
              </div>
            </div>

            <el-table 
              :data="videos" 
              style="width: 100%"
              v-loading="loading"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="cover_url" label="封面" width="120">
                <template #default="scope">
                  <img 
                    :src="scope.row.cover_url" 
                    :alt="scope.row.title" 
                    style="width: 100px; height: 60px; object-fit: cover; border-radius: 4px; cursor: pointer;"
                    @click="handleViewVideoDetail(scope.row)"
                  >
                </template>
              </el-table-column>
              <el-table-column prop="title" label="视频标题" min-width="200">
                <template #default="scope">
                  <div class="video-title" @click="handleViewVideoDetail(scope.row)">
                    {{ scope.row.title }}
                  </div>
                  <div class="video-meta">
                    <span class="category-tag">{{ scope.row.category_name || '未分类' }}</span>
                    <span class="duration">{{ scope.row.duration || '--:--' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="上传者" width="120">
                <template #default="scope">
                  <div>{{ scope.row.nickname || scope.row.username || '未知用户' }}</div>
                  <div class="username">{{ scope.row.username || '' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="数据统计" width="250">
                <template #default="scope">
                  <div class="stats">
                    <span class="stat-item">播放: {{ (scope.row.view_count || 0).toLocaleString() }}</span>
                    <span class="stat-item">点赞: {{ (scope.row.like_count || 0).toLocaleString() }}</span>
                    <span class="stat-item">收藏: {{ (scope.row.collect_count || 0).toLocaleString() }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag
                    :type="getStatusTagType(scope.row.status)"
                    size="small"
                  >
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="发布日期" width="140">
                <template #default="scope">
                  {{ scope.row.published_at ? new Date(scope.row.published_at).toLocaleDateString('zh-CN') : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <el-dropdown>
                    <el-button type="text" size="small">
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleViewVideoDetail(scope.row)">
                          <el-icon><View /></el-icon> 查看
                        </el-dropdown-item>
                        <el-dropdown-item @click="handleEditVideo(scope.row)">
                          <el-icon><Edit /></el-icon> 编辑
                        </el-dropdown-item>
                        <el-dropdown-item @click="handleToggleStatus(scope.row)">
                          <el-icon><SwitchButton /></el-icon>
                          {{ scope.row.status === 1 ? '设为草稿' : '发布' }}
                        </el-dropdown-item>
                        <el-dropdown-item 
                          @click="handleDeleteVideo(scope.row)"
                          divided
                          class="danger-text"
                        >
                          <el-icon><Delete /></el-icon> 删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Document, User, Menu, VideoPlay, ChatRound, Setting, SwitchButton, Upload, More, Search, Delete, View, Edit, VideoCamera, Refresh } from '@element-plus/icons-vue';
import type { Video } from '../api/videoService';

// 分页相关状态

const router = useRouter();
const userInfo = ref({ username: '', nickname: '', role: '' });
const searchQuery = ref('');
const videos = ref<Video[]>([]);
const loading = ref(false);
const multipleSelection = ref<Video[]>([]);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 筛选条件
const categoryId = ref<number | null>(null);
const userId = ref<number | null>(null);
const statusFilter = ref<number | null>(null);
const startDate = ref('');
const endDate = ref('');

const activeMenu = computed(() => {
  return window.location.pathname;
});

const getStatusText = (status: number): string => {
  switch (status) {
    case 1: return '已发布';
    case 0: return '草稿';
    default: return '未知';
  }
};

/**
 * 获取状态对应的标签类型
 * @param status 视频状态码
 * @returns Element Plus标签类型
 */
const getStatusTagType = (status: number): string => {
  switch (status) {
    case 1: return 'success';
    case 0: return 'warning';
    default: return 'info';
  }
};

/**
 * 处理查看视频详情
 * @param video 视频对象
 */
const handleViewVideoDetail = (video: Video) => {
  ElMessage.info(`查看视频详情: ${video.title}`);
  // 实际实现中可以这样：router.push({ path: '/video-detail', query: { id: video.id } });
};

const initData = () => {
  const userStr = localStorage.getItem('user');
  if (userStr) {
    userInfo.value = JSON.parse(userStr);
  }
};

const handleLogout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  ElMessage.success('退出登录成功');
  router.push('/login');
};

/**
 * 获取视频列表数据
 */
const fetchVideos = async () => {
  loading.value = true;
  
  // 开发环境默认使用模拟数据，避免API调用错误影响体验
  // 模拟数据将根据当前筛选条件进行过滤
  try {
    // 生成模拟数据
    const mockVideos = [
      {
        id: 1,
        title: '欧洲杯集锦2024',
        cover_url: 'https://placehold.co/800x450/3a3a3a/ffffff?text=体育视频',
        video_url: '',
        description: '精彩的欧洲杯足球赛事集锦',
        duration: '05:30',
        view_count: 123430,
        like_count: 10000,
        collect_count: 5000,
        share_count: 1000,
        category_id: 1,
        category_name: '体育',
        user_id: 1,
        username: 'sports_channel',
        nickname: '体育频道',
        status: 1,
        published_at: '2024-11-01T10:00:00Z',
        created_at: '2024-11-01T08:00:00Z',
        updated_at: '2024-11-01T10:00:00Z'
      },
      {
        id: 2,
        title: '芝士蛋糕：家常制作',
        cover_url: 'https://placehold.co/800x450/3a3a3a/ffffff?text=美食视频',
        video_url: '',
        description: '简单易学的芝士蛋糕制作教程',
        duration: '10:20',
        view_count: 89234,
        like_count: 8000,
        collect_count: 6000,
        share_count: 1500,
        category_id: 2,
        category_name: '美食',
        user_id: 2,
        username: 'food_master',
        nickname: '美食达人',
        status: 1,
        published_at: '2024-11-02T12:00:00Z',
        created_at: '2024-11-02T10:00:00Z',
        updated_at: '2024-11-02T12:00:00Z'
      },
      {
        id: 3,
        title: '旅行Vlog：探索东京',
        cover_url: 'https://placehold.co/800x450/3a3a3a/ffffff?text=旅游视频',
        video_url: '',
        description: '日本东京旅行见闻',
        duration: '15:45',
        view_count: 234567,
        like_count: 15000,
        collect_count: 8000,
        share_count: 3000,
        category_id: 3,
        category_name: '旅游',
        user_id: 3,
        username: 'traveler',
        nickname: '旅行家',
        status: 1,
        published_at: '2024-11-02T15:00:00Z',
        created_at: '2024-11-02T14:00:00Z',
        updated_at: '2024-11-02T15:00:00Z'
      },
      {
        id: 4,
        title: '前端教学：React入门',
        cover_url: 'https://placehold.co/800x450/3a3a3a/ffffff?text=科技视频',
        video_url: '',
        description: 'React框架入门教程',
        duration: '20:15',
        view_count: 45678,
        like_count: 6000,
        collect_count: 10000,
        share_count: 2000,
        category_id: 4,
        category_name: '科技',
        user_id: 4,
        username: 'code_academy',
        nickname: '编程学院',
        status: 0,
        published_at: null,
        created_at: '2024-11-03T09:00:00Z',
        updated_at: '2024-11-03T09:00:00Z'
      },
      {
        id: 5,
        title: '音乐MV：新歌发布',
        cover_url: 'https://placehold.co/800x450/3a3a3a/ffffff?text=音乐视频',
        video_url: '',
        description: '最新单曲音乐视频',
        duration: '03:45',
        view_count: 567890,
        like_count: 50000,
        collect_count: 20000,
        share_count: 10000,
        category_id: 5,
        category_name: '音乐',
        user_id: 5,
        username: 'music_channel',
        nickname: '音乐频道',
        status: 1,
        published_at: '2024-11-03T18:00:00Z',
        created_at: '2024-11-03T17:00:00Z',
        updated_at: '2024-11-03T18:00:00Z'
      }
    ];
    
    // 根据筛选条件过滤数据
    let filteredVideos = [...mockVideos];
    
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase();
      filteredVideos = filteredVideos.filter(video => 
        video.title.toLowerCase().includes(query)
      );
    }
    
    if (statusFilter.value !== null) {
      filteredVideos = filteredVideos.filter(video => 
        video.status === statusFilter.value
      );
    }
    
    // 处理分页
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    const paginatedVideos = filteredVideos.slice(startIndex, endIndex);
    
    // 更新状态
    videos.value = paginatedVideos;
    total.value = filteredVideos.length;
    
    // 仅在开发环境下显示此提示
    if (import.meta.env.DEV) {
      console.log('使用模拟数据显示视频列表');
    }
    
  } catch (error) {
    console.error('处理视频数据错误:', error);
    ElMessage.error('加载视频数据失败，请稍后重试');
    
    // 使用保底模拟数据
    videos.value = [
      {
        id: 1,
        title: '保底视频1',
        cover_url: 'https://placehold.co/800x450/3a3a3a/ffffff?text=保底视频',
        video_url: '',
        description: '保底视频描述',
        duration: '05:30',
        view_count: 10000,
        like_count: 500,
        collect_count: 300,
        share_count: 50,
        category_id: 1,
        category_name: '默认分类',
        user_id: 1,
        username: 'default_user',
        nickname: '默认用户',
        status: 1,
        published_at: '2024-11-01T10:00:00Z',
        created_at: '2024-11-01T08:00:00Z',
        updated_at: '2024-11-01T10:00:00Z'
      }
    ];
    total.value = videos.value.length;
  } finally {
    loading.value = false;
  }
};

/**
 * 处理搜索
 */
const handleSearch = () => {
  currentPage.value = 1;
  fetchVideos();
};

/**
 * 重置筛选条件
 */
const handleResetFilter = () => {
  searchQuery.value = '';
  categoryId.value = null;
  userId.value = null;
  statusFilter.value = null;
  startDate.value = '';
  endDate.value = '';
  currentPage.value = 1;
  fetchVideos();
};

/**
 * 处理上传视频
 */
const handleUploadVideo = () => {
  ElMessage.info('即将打开视频上传界面');
};

/**
 * 处理编辑视频
 * @param video 要编辑的视频对象
 */
const handleEditVideo = (video: Video) => {
  ElMessage.info(`编辑视频: ${video.title}`);
};

/**
 * 处理切换视频状态
 * @param video 要切换状态的视频对象
 */
const handleToggleStatus = async (video: Video) => {
  const newStatus = video.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '发布' : '设为草稿';
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    video.status = newStatus;
    ElMessage.success(`视频状态已${statusText}成功`);
  } catch (error) {
    console.error('更新视频状态错误:', error);
    ElMessage.error('更新视频状态失败，请稍后重试');
  }
};

/**
 * 处理删除视频
 * @param video 要删除的视频对象
 */
const handleDeleteVideo = async (video: Video) => {
  try {
    // 模拟确认对话框
    await new Promise(resolve => setTimeout(resolve, 300));
    // 从列表中移除
    videos.value = videos.value.filter(v => v.id !== video.id);
    total.value--;
    ElMessage.success('视频删除成功');
  } catch (error) {
    console.error('删除视频错误:', error);
    ElMessage.error('删除视频失败，请稍后重试');
  }
};

/**
 * 处理批量删除视频
 */
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的视频');
    return;
  }
  
  try {
    // 模拟确认对话框
    await new Promise(resolve => setTimeout(resolve, 300));
    const ids = multipleSelection.value.map(v => v.id);
    // 从列表中移除选中的视频
    videos.value = videos.value.filter(v => !ids.includes(v.id));
    total.value -= ids.length;
    multipleSelection.value = [];
    ElMessage.success(`成功删除 ${ids.length} 个视频`);
  } catch (error) {
    console.error('批量删除视频错误:', error);
    ElMessage.error('批量删除失败，请稍后重试');
  }
};

/**
 * 处理选择变更
 * @param selection 选中的视频数组
 */
const handleSelectionChange = (selection: Video[]) => {
  multipleSelection.value = selection;
};

/**
 * 处理分页变更
 * @param val 新的页码
 */
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchVideos();
};

/**
 * 处理每页数量变更
 * @param val 新的每页数量
 */
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchVideos();
};

onMounted(() => {
  initData();
  fetchVideos();
});
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  background-color: #1a1a1a;
}

.sidebar {
  background-color: #2a2a2a;
  height: 100vh;
}

.logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #3a3a3a;
}

.logo h3 {
  color: #ffffff;
  margin: 0;
}

.el-menu-vertical-dark {
  background-color: transparent;
  border-right: none;
}

.el-menu-item {
  color: #cccccc;
  margin: 0 10px;
  border-radius: 4px;
}

.el-menu-item:hover {
  background-color: #3a3a3a;
  color: #ffffff;
}

.el-menu-item.is-active {
  background-color: #409eff;
  color: #ffffff;
}

.header {
  background-color: #2a2a2a;
  color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #3a3a3a;
}

.user-info {
  margin-right: 20px;
  color: #cccccc;
}

.main-content {
  background-color: #1a1a1a;
  padding: 20px;
  overflow: auto;
}

.management-content h2 {
  color: #ffffff;
  margin-bottom: 5px;
}

.section-title {
  color: #999999;
  margin-bottom: 20px;
  font-size: 14px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.video-title {
  font-weight: 500;
  cursor: pointer;
  color: #ffffff;
  margin-bottom: 4px;
}

.video-title:hover {
  color: #409eff;
}

.video-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #999999;
}

.category-tag {
  background-color: #4a4a4a;
  padding: 2px 8px;
  border-radius: 4px;
}

.username {
  font-size: 12px;
  color: #999999;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
}

.stat-item {
  display: block;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-text {
  color: #f56c6c;
}

.el-pagination {
  color: #cccccc;
}

.el-pagination .btn-prev,
.el-pagination .btn-next {
  color: #cccccc;
}

.el-pagination .el-pager li {
  color: #cccccc;
}

.el-pagination .el-pager li.active {
  color: #ffffff;
  background-color: #409eff;
}

.el-table {
  background-color: #2a2a2a;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #3a3a3a;
  color: #ffffff;
  border-bottom: 1px solid #4a4a4a;
}

.el-table tr {
  background-color: #2a2a2a;
}

.el-table td {
  color: #cccccc;
  border-bottom: 1px solid #3a3a3a;
}

.el-table tr:hover > td {
  background-color: #3a3a3a;
}
</style>